<?php                                                                                                                                                                                                                          

/*

Query the database for point strings for polygons within given extents

*/

$path = dirname(dirname(__FILE__));

require($path.'/lib/crt.php');
require_once($path.'/lib/markets.php');

define('OUTPUT_DIR', "$path/export");

$crt = new CRT();
$crt->init();
$db = $crt->gisdb;

$exportFmt = Clean::string($_REQUEST['exportFmt'], false, false, true);
$exportObj = Clean::string($_REQUEST['exportObj'], false, false, true);
$exportMetro = $_REQUEST['exportMetro'] ? true : false;
$exportNhs = trim(Clean::string($_REQUEST['exportNhs'], false, false, true));

$sql = "SELECT max(dateModified) FROM crtLog";
$lastMod = $db->GetOne($sql);

// Generate unique integer to be used in all output file names 
$suffix = rand(10000, 30000);

// Array of neighborhood output files
$outfiles = array();

// Get the neighborhoods to export, assumed to be "all" if no nhs are specified
if($exportNhs) 
	$exportNhs = explode(',', $exportNhs);

if($exportNhs && count($exportNhs)) {
	foreach($exportNhs as &$n)
        	$n = $db->qstr($n);
        $nhSql = "AND name1 IN (".implode(',', $exportNhs).")";
}

if(false && $lastMod < $lastExp) {
	echo json_encode(true);
	exit;
}



if($exportObj=='blocks') {
	$sql = "SELECT oid, name1 as nh, blkidfp, name, objectid, point_string_simple from ".BLOCKS_TBL." WHERE 1=1 $nhSql ";
	$res = $db->GetArray($sql);

	$nhs = array();
	// group the blocks by nh
	foreach($res as $r) {
		$nh = $r['nh'];
		if(!$nhs[$nh])
			$nhs[$nh] = array($r);
		else
			array_push($nhs[$nh], $r);
	}

	// Loop through the neighborhoods
	foreach($nhs as $k => $n) {
		// Initialize output for one nh
		$outStr = '';

		// Loop through the blocks
		foreach($n as $b) {
			$outStr .= "{$b['oid']}\n{$b['nh']}\n{$b['blkidfp']}\n{$b['name']}\n";
			$points = getPoints($b['point_string_simple']);

			foreach($points as $p) {
	                	$p = explode(' ', $p);
		                if($p[1] && $p[0])
                		        $outStr .= "{$p[0]},{$p[1]}\n";
        		}

		        $outStr .= "END\n";
		}
		
		$fname = str_replace(' ', '', OUTPUT_DIR."/$k-$suffix.txt");
		$h = fopen($fname, 'w+');
		fwrite($h, $outStr);
		fclose($h);

		array_push($outfiles, $fname);
	}


} elseif($exportObj=='neighborhoods') {

	$sql = "SELECT
		name1 as nh
		, st.astext(ST.unionaggregate(st.transform(GIS_DATA,4326))) as point_string_simple
			FROM ".BLOCKS_TBL." WHERE name1 is not null and name1 <> '' $nhSql  GROUP BY name1";
	$res = $db->GetArray($sql);


	foreach($res as $b) {
	        //print_r($b); exit;
        	$outStr = '';

	        if(!$b['nh'])
        	        $b['nh'] = "Not named";

        	else
                	$outStr .= "{$b['nh']}\n";

	        $points = getPoints($b['point_string_simple']);

	        foreach($points as $p) {
        	        $p = explode(' ', $p);
                	if($p[1] && $p[0])
                        	$outStr .= "{$p[0]},{$p[1]}\n";
	        }

	        $outStr .= "END\n";

		$fname = str_replace(' ', '', OUTPUT_DIR."/{$b['nh']}-$suffix.txt");
                $h = fopen($fname, 'w+');
                fwrite($h, $outStr);
                fclose($h);

		array_push($outfiles, $fname);
	}


} else {
        echo json_encode(true);
        exit;

}


$dir = dirname(dirname(__FILE__));

$shapeFiles = array();

foreach($outfiles as $f) {
	$start = strlen(OUTPUT_DIR)+1;
	$pfx = substr($f, $start, strpos($f, '-')-$start);
	$shapePfx = 'outfile-'.$pfx.'-'.$suffix;
	exec($dir.'/gen2shp/gen2shp '.OUTPUT_DIR.'/'.$shapePfx.' polygons < '.$f);

	array_push($shapeFiles, $shapePfx);
}

$h = fopen(OUTPUT_DIR.'/'.$shapePfx.'.prj', 'w+');
fwrite($h, 'GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]');
fclose($h);


$zipStr = '';
foreach($shapeFiles as $s) {
	$shpPath = OUTPUT_DIR."/$s";

	if(file_exists("$shpPath.shp"))	
		$zipStr .= " $shpPath.shp";
	if(file_exists("$shpPath.dbf"))
                $zipStr .= " $shpPath.dbf";
	if(file_exists("$shpPath.shx"))
                $zipStr .= " $shpPath.shx";
	if(file_exists("$shpPath.prj"))
                $zipStr .= " $shpPath.prj";
		
}

$zipFile = OUTPUT_DIR .'/'.$suffix.'.zip';
exec("zip -j $zipFile $zipStr");

echo json_encode("/export/$suffix.zip");

// Update the log
$sql = "INSERT INTO exportLog (dateRun) values (getdate())";
$db->_Execute($sql);


// Return an array of points from a point string
function getPoints($pointStr) {
	$pointStr = str_replace('(', '', $pointStr);
        $pointStr = str_replace(')', '', $pointStr);
        $pointStr = str_replace('MULTIPOLYGON', '', $pointStr);
        $pointStr = str_replace('POLYGON', '', $pointStr);

        $points = explode(',', $pointStr);

	return $points;

}

?>
